package com.junxi.microservices.bookstore.product.config;

import feign.RequestInterceptor;
import io.micrometer.tracing.propagation.Propagator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.client.*;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import io.micrometer.tracing.Tracer;

@Configuration
public class FeignClientConfig {

    @Value("${product.oauth2.client-id}")
    private String clientId;
    
    @Value("${product.oauth2.client-secret}")
    private String clientSecret;
    
    @Value("${product.oauth2.token-uri}")
    private String tokenUri;
    
    @Value("${product.oauth2.scope}")
    private String scope;

    private final Tracer tracer;
    private final Propagator propagator;

    // 注入Micrometer Tracer和Propagator
    public FeignClientConfig(Tracer tracer, Propagator propagator) {
        this.tracer = tracer;
        this.propagator = propagator;
    }
    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientService authorizedClientService,
            OAuth2AuthorizedClientRepository authorizedClientRepository) {
        
        // 创建客户端注册信息
        ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("product-service-client")
                .clientId(clientId)
                .clientSecret(clientSecret)
                .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
                .tokenUri(tokenUri)
                .scope(scope)
                .build();
        
        // 注册客户端
        InMemoryClientRegistrationRepository registrationRepository = 
            new InMemoryClientRegistrationRepository(clientRegistration);
        
        // 创建客户端管理器
        OAuth2AuthorizedClientManager authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(
                registrationRepository, authorizedClientService);
//        DefaultOAuth2AuthorizedClientManager authorizedClientManager =
//                new DefaultOAuth2AuthorizedClientManager(
//                        clientRegistrationRepository, authorizedClientRepository);
        return requestTemplate -> {
            // 获取Client Credentials模式的令牌
            OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
                .withClientRegistrationId("product-service-client")
                .principal("product-service")
                .build();
                
            OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(authorizeRequest);
            
            if (authorizedClient != null && authorizedClient.getAccessToken() != null) {
                requestTemplate.header("Authorization", 
                    "Bearer " + authorizedClient.getAccessToken().getTokenValue());
            }

            // 从当前上下文获取跟踪信息并添加到请求头
            if (tracer.currentSpan() != null) {
                // 创建一个载体来存储跟踪头信息
                Propagator.Setter<HttpHeaders> setter = HttpHeaders::set;
                HttpHeaders headers = new HttpHeaders();

                // 使用 propagator 填充跟踪头
                propagator.inject(tracer.currentSpan().context(), headers, setter);

                // 将跟踪头添加到Feign请求中
                headers.forEach((key, values) -> {
                    if (!values.isEmpty()) {
                        requestTemplate.header(key, values.get(0));
                    }
                });
            }

//            // 从当前上下文获取跟踪信息并添加到请求头
//            if (tracer.currentSpan() != null) {
//                tracer.currentSpan().context().spanId()
//                        ;
//                requestTemplate.header()
//                tracer.currentSpan().context().forEach((key, value) -> {
//                    template.header(key, value.toString());
//                });
//            }

//            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
//                    .getRequestAttributes();
//            if (attributes != null) {
//                HttpServletRequest request = attributes.getRequest();
//                Enumeration<String> headerNames = request.getHeaderNames();
//                if (headerNames != null) {
//                    while (headerNames.hasMoreElements()) {
//                        String name = headerNames.nextElement();
//                        String value = request.getHeader(name);
//                        // 传递所有请求头，包括Sleuth的跟踪信息
//                        requestTemplate.header(name, value);
//                    }
//                }
//            }
        };
    }

    /**
     * 内存中的客户端注册仓库
     */
    private record InMemoryClientRegistrationRepository(
            ClientRegistration clientRegistration) implements ClientRegistrationRepository {

        @Override
        public ClientRegistration findByRegistrationId(String registrationId) {
            return clientRegistration;
        }
    }
}
